<template>
    <!-- highlightCurrenRow 在此组件无效  测试el-table 单独使用时可以有highlightCurrenRow效果 2022年10月24日 -->
    <!-- stripe 内部写死 :stripe="stripe" 会有失效的情况   -->
    <el-table tooltip-effect :data="tableData"  :height="height" @click.stop :stripe="true" :highlight-current-row="true" ref="customTable"
        @selection-change="handleSelectionChange"
        :header-cell-style="{backgroundColor:'transparent',color:'rgba(230, 253, 255, 0.60)',fontSize:'20px',fontFamily:'OPPOSans-Regular'}"
        :cell-style="{ backgroundColor:calcBc,'text-align': 'center',fontSize:'20px',color:'rgba(230, 253, 255, 0.80)',fontFamily:'OPPOSans-Regular' }"
        :row-style="{height:itemHeight}"
        >
        <el-table-column  v-if="showLabel" type="index" label="序号" width="80" >

 </el-table-column>

        <el-table-column fixed v-if="selectionColumn" type="selection" width="45" />
        <!-- :fixed="item.name == 'operation' ? 'right' : ''" -->
        <el-table-column :show-overflow-tooltip="item.type == 'LONGTEXTHIDDEN'" :prop="item.name"  :sortable="item.sortable===1"   v-for="(item, index) in currentFieldList"   :key="index" :label="item.label" header-align="center"
            
          :width="item.width"  :height="item.height"  :min-width=" item.itemWidth?item.itemWidth:item.type == 'SLOT' ? slotMinWidth : item.type == 'LONGTEXT' ? longTextMinWidth : normalMinWidth">
            <!-- <template v-if="index < maxColumnCount" #default="scope"> -->
            <template #default="scope">
                <!-- 带有匹配条件的 -->
                <div style=" display: flex; align-items: center;justify-content: center"   v-if="item.type == 'CONDITION'">
                    <!-- item.condiction  {{ scope.row[item.name] }} -->
              {{      dealcondition(item.condition,scope.row[item.name])}}
                </div>
                <!-- 长文本 -->
                <div style=" display: flex; align-items: center;justify-content: center"   v-if="item.type == 'LONGTEXT'">
                   {{ scope.row[item.name] }}
                </div>
                <!-- 长隐藏文本 -->

                <div    v-if="item.type == 'LONGTEXTHIDDEN'">
                   {{ scope.row[item.name] }}
                </div>
                <!-- <div  v-if="item.type == 'LONGTEXTHIDDEN'">
                <el-tooltip hide-after="100000" :content="scope.row.description" :disabled="false">
                   <span class="cell-ellipsis">{{ scope.row.description }}</span>
               </el-tooltip>
               </div> -->
                <!-- 时间 -->
                <div style=" display: flex; align-items: center;justify-content: center" v-else-if="item.type == 'TIME'">
                    <span>{{ toTime(scope.row[item.name]) }}</span>
                </div>

                <!-- 日期 -->
                <div style=" display: flex; align-items: center;justify-content: center" v-else-if="item.type == 'DATE'">
                    <span>{{ toDate(scope.row[item.name]) }}</span>
                </div>

                <!-- 日期时间 -->
                <div style=" display: flex; align-items: center;justify-content: center"
                    v-else-if="item.type == 'DATETIME'">
                    <span>{{ toDatetime(scope.row[item.name]) }}</span>
                </div>

                <!-- 图片 -->
                <div style=" display: flex; align-items: center;justify-content: center" v-else-if="item.type == 'IMAGE'">
                    <el-image style="width: 50px; height: 50px" :src="toUrl(scope.row[item.name])"
                        :preview-src-list="toUrls(scope.row[item.name])" fit="cover" :preview-teleported="true" />
                </div>

                <!-- 插槽 -->
                <slot  :name="item.name" :row="scope.row" v-else-if="item.type == 'SLOT'&&item.name!='operation'" >
                </slot>

                <!-- 短文本 -->
                <div style=" display: flex; align-items: center;justify-content: center" v-else-if="item.type == 'TEXT'" show-overflow-tooltip="true">
                    <span>{{ scope.row[item.name] }}</span>
                </div>
                <!-- TOOLTIP -->
                <div v-else-if="item.type == 'TOOLTIP'"  >
                    <el-tooltip class="item" :content="scope.row[item.name]" placement="right" popper-class="tooltip-width">
             <span class="text-no-wrap">{{ scope.row[item.name]}}</span>
               </el-tooltip>
                 </div>
            </template>
        </el-table-column>
            
        <el-table-column name="操作" fixed="right" v-if="operationTaget"  :min-width="slotMinWidth">
            <template #default="scope">
            <slot name="operation" :row="scope.row"  >
            </slot>
            </template>

        </el-table-column>
 

    </el-table>
</template>
    
<script setup lang='ts' >

import { getCurrentInstance, inject, onMounted, reactive, ref, toRaw } from 'vue'
import { useConvert } from '@/hook/useConvert'
import * as _ from "lodash"
// import { ElTable } from 'element-plus';


const { toDate, toDatetime, toTime, toUrls, toUrl } = useConvert()


interface TableField {
    name: string,
    label: string,
    type: 'TIME' | 'DATETIME' | 'DATE' | 'TEXT' | 'IMAGE' | 'LONGTEXT' | 'SLOT'
}

const props = defineProps({

    tableData: {
        type: Object,
        default: () => ([])
    },
    fieldList: {
        type: Object,
        default: () => ([])
    },
    height: {
        type: [Number, String],
        default: 300
    },
    longTextMinWidth: {
        type: String,
        default: "300px"
    },
    showLabel:{
        type: Boolean,
        default: true
    },
     itemHeight: {
        type: String,
        default: "40px"
    },
   //是否自动滚动
    openAutoscoll: {
        type: Boolean,
        default: true
    },

    //重写斑马纹默认值
    stripe: {
        type: Boolean,
        defalut: true
    },

    //重写点击行，高亮默认值 : 无用
    //  测试 直接使用el-table 在页面上 此值有用， 
    // 但是在调用组件的情况下，即使在组件内部直接 写 highlightCurrenRow（highlight-curren-row） 也无用
    highlightCurrenRow: {
        type: Boolean,
        defalute: true
    },

    //重写文本过长隐藏 : 无用
    // 测试时，加上此字段，即使是空的字符串，也会出现 tooltip
    showOverflowTooltip: {
        type: Boolean,
        defalute: true
    },

    //是否需要选择列
    // 搭配selectionColumnChange使用，此方法的第二个参数为ids 可以更快的进行删除操作
    selectionColumn: {
        type: Boolean,
        defalute: false
    },

    //更改插槽最小宽度 ，一般一个列只有一个插槽 按钮过多的话，可以尝试写宽一点
    slotMinWidth: {
        type: String,
        default: "190px"
    },

    //除了插槽以外的列的最小宽度，不建议使用此组件写可以横向拖动的table，
    //如果列数过多，不建议修改它，应该从fieldList入手，直接减少列数。也可以起到布局美观的作用
    normalMinWidth: {
        type: String,
        default: "120px"
    },
    propSort:{
        type: Object,
        default: () => ({})
    }

})
let currentFieldList:any = ref([])
currentFieldList.value = props.fieldList;

let operationTaget = ref(false);


for (let index = 0; index < currentFieldList.value.length; index++) {
    const element = currentFieldList.value[index];
    if (element.name=='operation') {
            currentFieldList.value.splice(index,1);
            operationTaget.value = true
    }   
    
}
const tableRowClassName=(rowIndex:any)=>{
 
 if (rowIndex.rowIndex % 2 != 0) {
   return 'evenRow';
 }
 return 'oddRow';
}

const calcBc=(rowIndex:any)=>{
 
 if (rowIndex.rowIndex % 2 != 0) {
   return 'transparent';
 }
 return 'rgba(20, 67, 81, 0.90)';
}
//获取当前选中列的方法
const emit = defineEmits(["selectionColumnChange"])
const handleSelectionChange = (vals: any[]) => {
    let ids: Array<String> = [];

    for (let val of vals) {
        if (val.id != undefined) {
            ids.push(val.id)
        }
    }
    emit("selectionColumnChange", vals, ids)
}


const dealcondition=(condition:Map<any,any>,item:any)=>{
return condition.get(item.toString())
}
import { ElTable } from 'element-plus';

// 声明 customTable 为 HTMLElement 类型或具体的 Element UI 表格类型
const customTable = ref<InstanceType<typeof ElTable> | null>(null);
let inter:any
onMounted(() => {
    nextTick(()=>{
        if(props.openAutoscoll){
            startAutoScroll(inter)
        }
    })
})
const CustomTable = ref(null)
let scrollInterval;

const startAutoScroll = (inter:any) => {
        scroll(inter);//设置滚动
};

const scroll = (inter:any) => {
  let isScroll = true;
  const dom1 = customTable.value?.$el.getElementsByClassName("el-scrollbar__wrap")[0];
//   避免出现元素过少抖动
   if(dom1.scrollHeight-dom1.clientHeight <=5){
    return
   }
  dom1.addEventListener("mouseover", () => {
    isScroll = false;
  });
  dom1.addEventListener("mouseout", () => {
    isScroll = true;
  });
  inter=setInterval(() => {
    if (isScroll) {
      dom1.scrollTop += 4;      
      if (dom1.clientHeight + dom1.scrollTop >= dom1.scrollHeight-1) {
        dom1.scrollTop = 0;       
      }   
    }
  }, 100);
};


const toggleRowSelection = (row:any,selected:boolean) => {
    (CustomTable.value as any).toggleRowSelection(row,selected);
}
onBeforeUnmount(() => {
if(inter&&props.openAutoscoll){
    clearInterval(inter);
}
});
defineExpose({
    toggleRowSelection
})

</script>
    

<style scoped lang="scss">
:depp .el-table{
  height: 100% !important;
}
:deep().el-table__inner-wrapper {
    height: 100% !important;
}

:deep .el-popper.is-dark {
    width: 300px;
}
//取消最下面白线
 :deep(.el-table__inner-wrapper::before) {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0;
      z-index: 3;
      }
  .evenRow {
  background: #1d6aad !important;
}
.oddRow{
  background:#1ba038 !important;
}
/* 定制斑马纹背景颜色 */
.text-no-wrap {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  vertical-align: middle;
  max-width: 100%;
}

</style>
<style lang="css"> 
.tooltip-width{
  width: 300px;
  font-size: 20px;
  font-family: 'OPPOSans-Regular';
}
</style>